<?php

function list_spl(){
	my_set_code_js('
		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete&id=\'+id;
			}
			return false;
		}	
	');
	$header = array(
		'NO. SPL'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'TGL SPL'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'NIK'=>array('style'=>'border-bottom:2px solid;width:8%'),    
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:20%'),    
		'DARI '=>array('style'=>'border-bottom:2px solid;width:6%'),    
		'KE'=>array('style'=>'border-bottom:2px solid;width:5%'),   
		'JM'=> array('style'=>'border-bottom:2px solid;width:4%'),  
		'TP'=>array('style'=>'border-bottom:2px solid;width:4%'),
    
		'PAY'=>array('style'=>'border-bottom:2px solid;width:4%'),  
		'tugas'=>array('style'=>'border-bottom:2px solid;width:20%'),  
 
		' '=>array('style'=>'text-align:right;border-bottom:2px solid;width:8%'), 
	);
	if(isset($_GET['av'])){
		if(isset($_GET['key']))
			$query = "SELECT * FROM a_spl a 
				INNER JOIN karyawan c ON a.karyawan_id = c.karyawan_id
				INNER JOIN biodata d ON d.biodata_id = c.biodata_id
				WHERE c.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable) AND 
				( c.nik='{$_GET['key']}' OR d.nama LIKE '%{$_GET['key']}%' OR a.nomor='{$_GET['key']}')
				  GROUP BY a.nomor ORDER BY a.spl_id DESC , a.tanggal DESC,a.nomor DESC";
		else
			$query = "SELECT * FROM a_spl ORDER BY  spl_id DESC , tanggal DESC,nomor DESC";
	}else{
		$periode_absen = get_periode_absen();
		$periode = my_get_data_by_id('pr_periode','periode_id',$periode_absen);
		$startdate = $periode['dari'];	
		$enddate  = $periode['sampai'];
		if(isset($_GET['key']))
			$query = "SELECT * FROM a_spl a 
				INNER JOIN karyawan c ON a.karyawan_id = c.karyawan_id
				INNER JOIN biodata d ON d.biodata_id = c.biodata_id
				WHERE  ( DATE(a.tanggal) >= '{$startdate}' AND DATE(a.tanggal) <='{$enddate}' )			
				AND c.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable) AND 
				( c.nik='{$_GET['key']}' OR d.nama LIKE '%{$_GET['key']}%' OR a.nomor='{$_GET['key']}')
				  GROUP BY a.nomor ORDER BY spl_id DESC , a.tanggal DESC,a.nomor DESC";
		else
			$query = "SELECT * FROM a_spl WHERE  ( DATE(tanggal) >= '{$startdate}' AND DATE(tanggal) <='{$enddate}' )	  GROUP BY nomor ORDER BY  spl_id DESC ,tanggal DESC,nomor DESC";
	}	 
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}".(isset($_GET['av']) ? "&av=true": '')."&task={$_GET['task']}&field={$_GET['field']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while( $ey = my_fetch_array($result) ){
		$periodes = my_get_data_by_id('pr_periode','periode_id',$ey['periode_id']);
		if( $ey['deleted']=='Y' ){
			$edit_button = button_icon( 'b_edit_off.png' , ''  );
			$delete_button = button_icon( 'b_drop_off.png' , ''  );
		}else{
			$editproperty = array(
				'href'=>'index.php?com='.$_GET['com'].'&task=edit&id='.$ey['spl_id'],
				'rel'=>'facebox',
				'title'=>'Edit'
			);
			$edit_button = button_icon( 'b_edit.png' , $editproperty  );
			$deleteproperty = array(
				'href'=>'javascript:; ',
				'onclick'=>'javascript:confirmDelete('.$ey['spl_id'].');',
				'title'=>'Delete'
			);
			$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		}
		$query = "SELECT * FROM a_spl_det
			WHERE spl_id={$ey['spl_id']} 
			ORDER BY spl_det_id DESC" ;
		$res_pos=my_query($query) ;	
		if(my_num_rows($res_pos)>1){
			$detailproperty = array(
				'href'=>'index.php?com=spl&task=list_koreksi&spl_id='.$ey['spl_id'].(isset($_GET['av']) ? "&av=true": ''),
				'title'=>'History'
			);
			$detail_button = button_icon( 'b_browse.png' , $detailproperty  );
			if($ey['deleted']=="Y"){
				$keterangan="Hapus" ;
			}else{
				$keterangan="Koreksi" ;
			}
		}else{
			$detail_button = '&nbsp; &nbsp;';
			$keterangan=" " ;
		}
		$det = my_get_data_by_id('a_spl_det' , 'spl_id' , $ey['spl_id'] );
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$row[] = array(
			'spl'=> strtoupper($ey['nomor'])  ,
			'tanggal'=>date('d-m-Y' , strtotime($ey['tanggal']) ),
			'nik'=> strtoupper($karyawan['nik'])  ,
			'nama'=> strtoupper($karyawan['nama_gelar'])  ,
			'dari'=>   date('H:i',strtotime( $ey['dari_jam']) )  ,
			'sampai'=> date('H:i',strtotime( $ey['sampai_jam']) )  ,
'jam'=>  $ey['jumlah_jam']   ,			
'tp'=>  $det['jenis_hari']   ,
'pay'=>  $ey['hitung_jam']   ,
'tugas'=>  $ey['tugas']   , 
			''=>position_text_align( $edit_button.' '.$delete_button/*.' '.$detail_button */,'right')
		);
	}
	$datas = table_rows($row);
	if(isset($_GET['av'])){
		$menuontop = array(  
			'Tambah data'=>array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=edit&id=0\' });'),
			'This Periode '=>array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'\'')
			//'Export to excel'=>array('onclick'=>'javascript:location.href=\'index.php?com=csv&task=excel_daftar_karyawan\''),
			//'Cetak' => array('onclick'=>'javascript:window.open(\'index.php?com=report&task=all_karyawan\',\'mywin\',\'left=20,top=20,width=800,height=600,toolbar=0,resizable=0\');')
		);
	}else{
		$menuontop = array(  
			'Tambah data'=>array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com='.$_GET['com'].'&task=edit&id=0\' });'),
			'All Periode'=>array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&av=true\' '),
			'Excel'=>array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&task=excel_lembur\''),
			//'Cetak' => array('onclick'=>'javascript:window.open(\'index.php?com=report&task=all_karyawan\',\'mywin\',\'left=20,top=20,width=800,height=600,toolbar=0,resizable=0\');')
		);
	} 
	$search = '<form method="GET">
	<input type="hidden" name="com" value="'.$_GET['com'].'" />
	'.(isset($_GET['av']) ? '<input type="hidden" name="av" value="'.$_GET['av'].'" />':'' ).'
	<span style="font:10px verdana"><b>Pencarian cepat</b></span>
	<br/><input type="text"  style="width:200px;" name="key" value="'.(isset($_GET['key']) ? $_GET['key']: "").'" />
	<input class="simple_search" type="submit" value=" CARI " />  </form>';
	$printmenu = additional_menu_on_list( $menuontop , $search);

	$periode_id = get_periode_absen();
	$periodes = my_get_data_by_id('pr_periode','periode_id',$periode_id);
	$view  = form_header( "..." , "..."  );
	$view .=form_field_display( '<span class="label_form">'. 
		 ( !isset($_GET['av']) ? date('d-m-Y' , strtotime($periodes['dari']) ) .' &nbsp; s/d &nbsp; '.date('d-m-Y' , strtotime($periodes['sampai']) ) : " Semua data lembur " )
		.'</span>'   , "<b>Periode Absen </b>"    ) ;
	$view  .= form_footer(  );
		
	$paging = $kgPagerOBJ ->showPaging();
	return $view.$printmenu . table_builder($header , $datas ,  8 , false ,$paging);
}



function calculate_hourpay( $hour , $daytype   ){
	 
	$hourpay = 0;
	for($i=1; $i<=$hour; $i++){
		
		//JAM PERTAMA
		if($i <= 1 ){
			if($daytype == 'HL'){
				//HARI LIBUR
				$hourpay +=  2;
				
			}elseif( $daytype == 'HR'){
				//HARI RAYA
				$hourpay +=   3;
			}else{
				//HARI BIASA
				$hourpay +=  1.5;
			}
			
		}
		//JAM KEDUA
		elseif($i <= 8){
			if($daytype == 'HL'){
				//HARI LIBUR
				$hourpay +=  2;
				
			}elseif( $daytype == 'HR'){
				//HARI RAYA
				$hourpay +=   3;
				
			}else{
				//HARI BIASA
				$hourpay +=   2;
			} 
		}else{
			//DIATASA JAM 8
			if($daytype == 'HL'){
				//HARI LIBUR
				$hourpay +=   3;
				
			}elseif( $daytype == 'HR'){
				//HARI RAYA
				$hourpay +=   4;
				
			}else{
				//HARI BIASA
				$hourpay +=   2;
			} 
		}
	}
	return $hourpay;
} 

function form_spl_create($id=0){
	my_set_file_js(
		array(
			'components/system/jquery/combomulti/jquery.chainedSelects.js',
			'components/system/js/calendar/calendarDateInput.js',
			'components/system/jquery/autocomplete/jquery.autocomplete.js' , 
		)
	);

	my_set_file_css(

		array(
				'components/system/jquery/autocomplete/jquery.autocomplete.css' 
			)
	);


	my_set_code_js('  
		function findValue(li) {
			if( li == null ) return alert("No match!"); 
			if( !!li.extra ) var sValue = li.extra[0]; 
			else var sValue = li.selectValue;
		}

		function selectItem(li) {
			findValue(li);
		}

		function formatItem(row) {
				return   row[0] ;
		}

		function lookupAjax(){
			var oSuggest = $("#nama_karyawan")[0].autocompleter;
			oSuggest.findValue(); 
			return false;
		}
		$(document).ready(function() {
			$("#nama_karyawan").autocomplete(
				"autocomplete_daftar_karyawan.php",
				{
					delay:10,
					minChars:2,
					matchSubset:1,
					matchContains:1,
					cacheLength:5,
					onItemSelect:selectItem,
					onFindValue:findValue,
					formatItem:formatItem,
					autoFill:true
				}
			);
			 
		});

		function checkName(name){
			$.get("check_karyawan_names.php", { nama: name  },
			   function(data){
				 if(data ==  \'0\' ){
					alert(\'Nama karyawan \'+ name+\' tidak ditemukan\nHarap diperiksa kembali\');
					$(\'#nama_karyawan\').val(\'\');
					return false;
				 } 
			   });
		}
		function getShift( ){
			var day = $(\'#tanggal_Day_ID\').val();
			var mon =  $(\'#tanggal_Month_ID\').val();
			var yer = $(\'#tanggal_Year_ID\').val();
			var  da = yer +\'-\'+ (parseFloat(mon)+parseFloat(1 ))+\'-\'+day;
			var name = $(\'#nama_karyawan\').val();
			$.get("get_karyawan_schedule.php", { nama: name , date:da ,check :1 },
			   function(data){
					var mySplitResult = data.split("|");  
					if(mySplitResult[3] == 1){
						alert(\'Golongan Jabatan Karyawan Tidak Dapat Lembur\');
					}
					$(\'#jadwal_kerja\').replaceWith(\'<span id="jadwal_kerja">\'+ mySplitResult[0] +\'</span>\');
					$(\'#realisasi_kerja\').replaceWith(\'<span id="realisasi_kerja">\'+ mySplitResult[1] +\'</span>\');
					$(\'#administrasi\').replaceWith(\'<span id="administrasi">\'+ mySplitResult[2] +\'</span>\');
					return false;
				 
			   });
		}
	'); 
	$view = form_header( "spl" , "spl"  );
 	$fields = my_get_data_by_id('a_spl','spl_id',$id);
	if($id==0){
		$nomor=  date('Ym').get_nomor_baru() ;
	}else{
		$nomor= $fields['nomor'];
	} 
 	
	$nomor = array(
		'name'=>'nomor',
		'value'=>( isset($_POST['nomor']) ? $_POST['nomor'] : $nomor ),
		'id'=>'nomor',
		'type'=>'text',
		'readonly'=>'readonly',
		'size'=>'25'
	);
	$form_field_code = form_dynamic($nomor);
	$view .= form_field_display( $form_field_code   , "No. SPL"   );
 	 
	$tanggal = array(
		'name'=>'tanggal',
		//'value'=>( isset($_POST['tanggal']) ? $_POST['tanggal'] : ( $fields ? date('d-m-Y',strtotime($fields['tanggal'])) : date('d-m-Y') ) ),
		'value'=>( isset($_POST['tanggal']) ? $_POST['tanggal'] : ( $fields ? date('d-m-Y',strtotime($fields['tanggal'])) : ( isset($_GET['pdate']) ? $_GET['pdate'] : date('d-m-Y') ) ) ),
		
		'id'=>'tanggal',
		'type'=>'tanggal',
		'size'=>'45'
	);
	$form_field_major = form_calendar($tanggal); 
	$view .= form_field_display( $form_field_major  , "Tanggal SPL"  ); 
	$tombol_check = array(
		'value' => ( 'Chk'),
		'name' => 'simpan', 
		'type'=>'button',
		'onclick'=>'javascript:getShift()',
		'class'=>'simple_button'
	);
	$form_tombol_check= form_dynamic($tombol_check); 
	
	$karyawan = loaddata_karyawan($fields['karyawan_id']);	
	$nama_karyawan = '';
	if($karyawan){
		$nama_karyawan = $karyawan['nik'].'/'.$karyawan['nama'] ;
	}
	
	$nama_karyawan = array(
		'name'=>'nama_karyawan',
		'value'=>( isset($_POST['nama_karyawan']) ? $_POST['nama_karyawan'] :$nama_karyawan ),
		'id'=>'nama_karyawan' , 
		'type'=>'text',
		'size'=>'45' ,
		'onchange'=>'javascript:checkName(this.value);'
	);
	$form_field_nama_karyawan = form_dynamic($nama_karyawan);
	$view .= form_field_display( $form_field_nama_karyawan /*.$form_tombol_check */ , "NIK / Nama karyawan"    );
	
	//$view .= form_field_display(  '<span id="jadwal_kerja"></span>' , "Jadwal kerja"    ); 
	//$view .= form_field_display(  '<span id="realisasi_kerja"></span>' , "Realisasi kerja"    ); 
	//$view .= form_field_display(  '<span id="administrasi"></span>' , "Administrasi"    ); 
	$dari_jam = array(
		'name'=>'dari_jam',
		'value'=>( isset($_POST['dari_jam']) ? $_POST['dari_jam'] : $fields['dari_jam'] ),
		'id'=>'dari_jam', 
	);
	$form_field_dari_jam = form_time($dari_jam);
	$sampai_jam = array(
		'name'=>'sampai_jam',
		'value'=>( isset($_POST['sampai_jam']) ? $_POST['sampai_jam'] : $fields['sampai_jam'] ),
		'id'=>'sampai_jam', 
	);
	$form_field_sampai_jam = form_time($sampai_jam); 
	$view .= form_field_display( $form_field_dari_jam .' s/d '. $form_field_sampai_jam , "Waktu"  );
	
	$tugas = array(
		'name'=>'tugas',
		'value'=>( isset($_POST['tugas']) ? $_POST['tugas'] : $fields['tugas'] ),
		'id'=>'tugas',
	);
	$form_field_tugas = form_textarea($tugas); 
	$view .= form_field_display(  $form_field_tugas  , "Tugas"  );

	$view .= form_field_display(  '<input type="checkbox" name="create_other" value="true" /> Munculkan form data baru'  , "&nbsp;"  );
	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 

	$view .= form_field_display( $form_submit .' '.$form_back , "&nbsp;" ,  "" );
	$view .= form_footer( );
	return $view;
}

function spl_validate( $id = 0){
	$errsubmit = false;
	$err = array();
	 
	list($dd,$mm,$yyyy) = explode("-",$_POST['tanggal']);
	$tanggal = $yyyy.'-'.$mm.'-'.$dd;
	if(!$tanggal){
		$errsubmit = true;
		$err[] = "Tanggal tidak benar";	
	}
	
	$code =  trim($_POST["nama_karyawan"]); 
	if( $code == '' OR $code == '/'){
		$errsubmit = true;
		$err[] ="Nama karyawan  belum diisi";
	}
		
	$karyawan_id= check_karyawan_by_nik_nama($_POST['nama_karyawan']);
	if($karyawan_id == 0){
		$errsubmit = true;
		$err[] = "Nama karyawan tidak di temukan";	
	}else{
		$karyawans=loaddata_karyawan($karyawan_id);
		$gols=my_get_data_by_id('golongan_jabatan','golongan_jabatan_id',$karyawans['golongan_jabatan_id']);
		if($gols['lembur']<>'Y'){
			$errsubmit = true;
			$err[] = "Golongan ".$gols['kode_golongan_jabatan']." tidak dapat lembur";
		}
	}	
	$dari = set_post_time_data('dari_jam');
	$sampai = set_post_time_data('sampai_jam');
	if($dari=='00:00' OR $sampai=='00:00'  ){
		$errsubmit = true;
		$err[] = "Jam lembur belum benar";
	}
	
	if( $errsubmit){
		return $err;
	}
	
	return $errsubmit;
}

function spl_submit($id=0){
	list($dd,$mm,$yyyy) = explode("-",$_POST['tanggal']);
	$tanggal = $yyyy.'-'.$mm.'-'.$dd;	
	$karyawan_id= check_karyawan_by_nik_nama($_POST['nama_karyawan']);
	$dari = set_post_time_data('dari_jam');
	$sampai = set_post_time_data('sampai_jam');
	$jumlah_jam=(int) date("H",strtotime(time_min($sampai,$dari)));
	
	$query = "SELECT hari_raya FROM a_hari_libur WHERE tanggal= '".$tanggal."'";
	$result = my_query($query);
	$jenis_hari="X";
	while( $ey1 = my_fetch_array($result) ){
		if($ey1['hari_raya']=="Y"){
			$jenis_hari="HR";
			break;
		}else{
			$jenis_hari="HL";
		}	
	}
	if($jenis_hari=="X"){
		if(is_sabtu_minggu($tanggal)){
			$jenis_hari="HL";
		}else{
			$jenis_hari="HB";
		}
	}	
	$query = "SELECT * FROM a_spl_tarif WHERE jenis_hari='".$jenis_hari."'";
	$result = my_query($query);
	$row=array();
	$nno=0;
	while( $ey1 = my_fetch_array($result) ){
		$row[] = array(
			'jam'=>$ey1['jam'] ,	
			'pengali'=>$ey1['pengali'] ,	
		);	
	}
	//asumsi masing jenis hari hanya punya 2 jenis pengali
	$batas_jam=(int) $row[1]['jam'];
	$batas_jam--;  //batas jam kedua dikurang 1
	$pengali_pertama=$row[0]['pengali'] ;
	$pengali_kedua=$row[1]['pengali'] ;
	$jam_pertama=max(0,$batas_jam);
	$jam_kedua=max(0,$jumlah_jam-$batas_jam);
	if($jumlah_jam<1){
		$hourpay=1;
	}else{	
		$hourpay=($jam_pertama*$pengali_pertama)+($jam_kedua*$pengali_kedua) ;
	}	
	$periode_absen = get_periode_absen();	
	if( $id>0){
		$spls=my_get_data_by_id('a_spl','spl_id',$id) ;
		if( (int) $spls['periode_id'] <> $periode_absen ){		
			$spl_det_id=0 ;
			$jenis='Koreksi' ;	
		}else{
			$query = "SELECT max(spl_det_id) as spl_det_id  FROM a_spl_det WHERE spl_id={$id}";
			$spl_dets = my_fetch_array(my_query($query));
			$spl_det_id = isset( $spl_dets['spl_det_id'] ) ? (int) $spl_dets['spl_det_id']:  0;
			$spl_dets = my_get_data_by_id('a_spl_det','spl_det_id',$spl_det_id );
			$jenis=$spl_dets['jenis'] ;	
		}
	}else{	
		$spl_det_id=0 ;	
		$jenis='Tambah' ;		
	}
	//update a_spl
	$hitung_jam = calculate_hourpay( $jumlah_jam, $jenis_hari  );
	$datas = array(
		'tanggal'=>my_type_data_str($tanggal),
		'periode_id'=>my_type_data_int( $periode_absen ),
		'nomor'	=>	 my_type_data_str(  $_POST['nomor'] 	),	
		'karyawan_id'=>my_type_data_int($karyawan_id ),
		'dari_jam'=>my_type_data_str($dari),
		'sampai_jam'=>my_type_data_str($sampai),
		'tugas'=>my_type_data_str($_POST['tugas']),
		'jumlah_jam'=>my_type_data_int($jumlah_jam),
		'hitung_jam'=>my_type_data_int($hitung_jam),
		'deleted'=>my_type_data_str( 'T' ),
	);
	
	if( $id > 0 ){
		my_update_record( 'a_spl' ,'spl_id' , $id , $datas );
	}else{
		$id= my_insert_record( 'a_spl' , $datas );	
	}	
		
	//update a_spl_det
	$datas = array(
		'jenis'=>my_type_data_str($jenis),
		'spl_id'=>my_type_data_int( $id ),
		'tanggal'=>my_type_data_str($tanggal),
		'periode_id'=>my_type_data_int( $periode_absen ),
		'karyawan_id'=>my_type_data_int($karyawan_id ),
		'dari_jam'=>my_type_data_str($dari),
		'sampai_jam'=>my_type_data_str($sampai),
		'jumlah_jam'=>my_type_data_int($jumlah_jam),
		'jenis_hari'=>my_type_data_str($jenis_hari),
		'hourpay'=>my_type_data_str($hourpay),
	);
	if( $spl_det_id > 0 ){
		my_update_record( 'a_spl_det' ,'spl_det_id' , $spl_det_id , $datas );
	}else{
		$spl_det_id=my_insert_record( 'a_spl_det' , $datas );
	}	
	update_a_spl_jam($id) ;
}	

function delete_spl($id){
	if(is_koreksi($id)){
		$periode_absen = get_periode_absen();	
		$spls=my_get_data_by_id('a_spl','spl_id',$id) ;
		$query = "DELETE FROM a_spl_det WHERE spl_id =  {$id} AND periode_id = {$periode_absen}";
		my_query($query);
		$datas = array(
			'spl_id'=>my_type_data_int( $spls['spl_id'] ),
			'tanggal'=>my_type_data_str( $spls['tanggal'] ),
			'jenis'=>my_type_data_str( 'Hapus' ), 	
			'karyawan_id'=>my_type_data_int($spls['karyawan_id'] ),
			'dari_jam'=>my_type_data_str( '00:00:00'),
			'sampai_jam'=>my_type_data_str( '00:00:00' ),
			'jumlah_jam'=>my_type_data_int( 0 ),
			'jenis_hari'=>my_type_data_str(''),
			'hourpay'=>my_type_data_str(''),			
			'periode_id'=>my_type_data_int( $periode_absen ),
		);
		$spl_det_id=my_insert_record( 'a_spl_det' , $datas );	
		$datas = array(
			'periode_id'=>my_type_data_int( $periode_absen ),
			'deleted'=>my_type_data_str( 'Y' ),
		); 
		my_update_record('a_spl' ,'spl_id' , $id , $datas);	
		return true;
	}else{
		$query = "DELETE FROM a_spl_jam WHERE spl_id = {$id}";
		my_query($query);
		$query = "DELETE FROM a_spl_det WHERE spl_id =  {$id}";
		my_query($query);
		$query = "DELETE FROM a_spl WHERE spl_id = {$id}";
		return my_query($query);
	}
}	

//	======================================= KOREKSI ===================================

function list_koreksi($spl_id){
	my_set_code_js('

		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete_koreksi&id=\'+id;
			}
			return false;
		}

	');

	$header = array(
		'Transaksi'=>array('style'=>'border-bottom:2px solid;width:20%'),    
		'NIK'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:25%'),    
		'Tanggal'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'DARI (JAM)'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'SAMPAI (JAM)'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'Periode'=>array('style'=>'border-bottom:2px solid;width:5%'),    
		' '=>array('style'=>'text-align:center;border-bottom:2px solid;width:10%'), 
	);
	if(isset($_GET['key'])){
		$query = "SELECT * FROM a_spl_det a 
			INNER JOIN karyawan c ON a.karyawan_id = c.karyawan_id
			INNER JOIN biodata d ON d.biodata_id = c.biodata_id
			WHERE spl_id={$spl_id} 
			AND c.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable) 
			AND ( c.nik='{$_GET['key']}' OR d.nama LIKE '%{$_GET['key']}%')
			 ORDER BY a.spl_det_id DESC";
	}else{
		$query = "SELECT * FROM a_spl_det WHERE spl_id={$spl_id} ORDER BY spl_det_id DESC";
	}	
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&spl_id={$_GET['spl_id']}&field={$_GET['field']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while( $ey = my_fetch_array($result) ){
		$periodes = my_get_data_by_id('pr_periode','periode_id',$ey['periode_id']);
		$periode_absen = get_periode_absen();
		if( (int) $ey['periode_id']== (int) $periode_absen){
			$deleteproperty = array(
					'href'=>'javascript:; ',
					'onclick'=>'javascript:confirmDelete('.$ey['spl_det_id'].');',
					'title'=>'Hapus Koreksi'
			);
			$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		}else{
			$delete_button = ' ' ;
		}
		 
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$row[] = array(
			'jenis'=>$ey['jenis'],
			'nik'=> strtoupper($karyawan['nik'])  ,
			'nama'=> strtoupper($karyawan['nama_gelar'])  ,
			'tanggal'=>date('d-m-Y' , strtotime($ey['tanggal']) ),			
			'dari'=>   date('H:i',strtotime( $ey['dari_jam']) )  ,
			'sampai'=> date('H:i',strtotime( $ey['sampai_jam']) )  ,
			'periode'=>date('m-Y' , strtotime($periodes['tanggal']) ),
			''=>position_text_align($delete_button ,'right')		
		);
	}
	$datas = table_rows($row);
	$menuontop = array(  
		'Kembali' => array('onclick'=>'javascript:location.href=\'index.php?com=spl'.(isset($_GET['av']) ? "&av=true": '').'\'')
	);	
	$spls = my_get_data_by_id('a_spl','spl_id',$spl_id );
	$view  = form_header( "..." , "..."  );
	$view .=form_field_display( '<span class="label_form">'.  $spls['nomor'].'</span>'   , "<b>No. SPL</b>"    ) ;
	$view  .= form_footer(  );
	
	$search = '<form method="GET">
	<input type="hidden" name="com" value="'.$_GET['com'].'" />
	<input type="hidden" name="spl_id" value="'.$_GET['spl_id'].'" />
	<span style="font:10px verdana"><b>Pencarian cepat</b></span>
	<br/><input type="text"  style="width:200px;" name="key" value="'.(isset($_GET['key']) ? $_GET['key']: "").'" />
	<input class="simple_search" type="submit" value=" CARI " />  </form>';
	$printmenu = additional_menu_on_list( $menuontop , $search);

	$paging = $kgPagerOBJ ->showPaging();
	return $view.$printmenu . table_builder($header , $datas ,  8 , false ,$paging);
}


function delete_koreksi($spl_det_id){
	$periode_absen = get_periode_absen();
	$spls=my_get_data_by_id('a_spl_det','spl_det_id',$spl_det_id) ;
	$spl_id = isset( $spls['spl_id'] ) ? (int) $spls['spl_id']:  0;	
	$query = "SELECT * FROM a_spl_det
		WHERE spl_id={$spl_id}  AND spl_det_id<{$spl_det_id} 
		ORDER BY spl_det_id DESC
		LIMIT 1" ;
	$spl_koreksis = my_fetch_array(my_query($query)) ;
	$datas = array(
		'tanggal'=>my_type_data_str( $spl_koreksis['tanggal'] ),
		'periode_id'=>my_type_data_int( $spl_koreksis['periode_id'] ),
		'karyawan_id'=>my_type_data_int($spl_koreksis['karyawan_id'] ),
		'dari_jam'=>my_type_data_str( $spl_koreksis['dari_jam'] ),
		'sampai_jam'=>my_type_data_str( $spl_koreksis['sampai_jam'] ),
		'jumlah_jam'=>my_type_data_int( $spl_koreksis['jumlah_jam'] ),
		'deleted'=>my_type_data_str( 'T' ),
		);
	my_update_record('a_spl' ,'spl_id' , $spl_id , $datas);	
	update_a_spl_jam($spl_id);
	$query = "DELETE FROM a_spl_det WHERE spl_det_id = {$spl_det_id}";
	return my_query($query);
}


/*
	======================================= FUNCTIONS ===================================
*/

function is_koreksi($id){
	$periode_absen = get_periode_absen();
	$query = "SELECT * FROM a_spl_det
		WHERE spl_id={$id}  AND jenis='Tambah'
		LIMIT 1" ;
	$spl_koreksis = my_fetch_array(my_query($query)) ;
	$periode_id=(int) $spl_koreksis['periode_id'] ;
	if($periode_id<$periode_absen){
		return true;
	}		
	return false;
}

function get_nomor_baru(){
	$query = "SELECT max(spl_id ) AS mmax FROM a_spl WHERE YEAR(tanggal ) = YEAR(NOW())";
	$result = my_query($query);
	$row = my_fetch_array($result);
	return sprintf('%05d' , $row['mmax'] +1);
}

function spl_kalkulasi(){  //dummy cara panggil = http://localhost/hris/index.php?com=spl&task=spl_kalkulasi
	$karyawan_id=2 ;
	$periode_id =get_periode_absen();
	$query = "SELECT * FROM a_spl_det 
			WHERE karyawan_id={$karyawan_id} 
			AND periode_id={$periode_id} 
			" ;	
	$res = my_query($query);
	$hourpay=0;
	while($ey1 = my_fetch_array($res)){
		if($ey1['jenis']=="Koreksi" or $ey1['jenis']=="Hapus")	{	
			$query = "SELECT * FROM a_spl_det	
				WHERE spl_id={$ey1['spl_id']}  AND spl_det_id<{$ey1['spl_det_id']} 
				ORDER BY spl_det_id DESC
				LIMIT 1" ;
			$spl_koreksis = my_fetch_array(my_query($query)) ;	
			$hourpay-=$spl_koreksis['hourpay'] ;
		}	
		if($ey1['jenis']=="Koreksi" or $ey1['jenis']=="Tambah")	{	
			$hourpay+=$ey1['hourpay'] ;
		}	
	}
	return true;//	var_dump($hourpay) ; exit;
}


function update_a_spl_jam($spl_id){	
	$spls = my_get_data_by_id('a_spl','spl_id',$spl_id );
	$total_fdate = strtotime( $spls['tanggal']) + 24 * 60 * 60;
	$tanggal_next = date('Y-m-d', $total_fdate);	
	//update a_spl_jam
	my_query("DELETE FROM a_spl_jam WHERE spl_id = {$spl_id}");  //reset
	if( strtotime( $spls['sampai_jam'] ) < strtotime( $spls['dari_jam'] )  ){
		$lintas_hari=true;
		$tmp_sampai='24:00'; 
		$tmp_dari='00:00'; 
	}else{
		$lintas_hari=false;
		$tmp_sampai=$spls['sampai_jam'] ;
	}
	$datas = array(
		'spl_id'=>my_type_data_int( $spl_id ),
		'tanggal'=>my_type_data_str($spls['tanggal']),
		'dari_jam'=>my_type_data_str($spls['dari_jam']),
		'sampai_jam'=>my_type_data_str($tmp_sampai),
	);
	my_insert_record( 'a_spl_jam' , $datas );	
	
	if( $lintas_hari ){
		$datas = array(
			'spl_id'=>my_type_data_int( $spl_id ),
			'tanggal'=>my_type_data_str($tanggal_next),
			'dari_jam'=>my_type_data_str($tmp_dari),
			'sampai_jam'=>my_type_data_str($spls['sampai_jam']),
		);
		my_insert_record( 'a_spl_jam' , $datas );	
	
	}
}


function spl_excel(){
	$header = array(
		'NO. SPL'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'TGL SPL'=>array('style'=>'border-bottom:2px solid;width:10%'),    
		'NIK'=>array('style'=>'border-bottom:2px solid;width:8%'),    
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:20%'),    
		'DARI '=>array('style'=>'border-bottom:2px solid;width:6%'),    
		'KE'=>array('style'=>'border-bottom:2px solid;width:6%'),     
		'JAM'=>array('style'=>'border-bottom:2px solid;width:6%'),  
		'TYPE'=>array('style'=>'border-bottom:2px solid;width:6%'),
		'HOURPAY'=>array('style'=>'border-bottom:2px solid;width:4%'),
		'tugas'=>array('style'=>'border-bottom:2px solid;width:22%'),   
	);
	$periode_absen = get_periode_absen();
	$query = "SELECT * FROM a_spl 
		WHERE periode_id ={$periode_absen}  
		GROUP BY nomor ORDER BY  spl_id DESC ,tanggal DESC,nomor DESC";
	$i = 0; 
	$result = my_query($query);
	while( $ey = my_fetch_array($result) ){
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$det = my_get_data_by_id('a_spl_det' , 'spl_id' , $ey['spl_id'] );
		$row[] = array(
			'spl'=> strtoupper($ey['nomor'])  ,
			'tanggal'=>date('d-m-Y' , strtotime($ey['tanggal']) ),
			'nik'=> "'".strtoupper($karyawan['nik'])  ,
			'nama'=> strtoupper($karyawan['nama_gelar'])  ,
			'dari'=>   "'".date('H:i',strtotime( $ey['dari_jam']) )  ,
			'sampai'=> "'".date('H:i',strtotime( $ey['sampai_jam']) )  ,
			'jam'=>  $ey['jumlah_jam'] ,
			'type'=>  $det['jenis_hari'] ,
			'hpay'=>  $ey['hitung_jam'] ,
			'tugas'=>  $ey['tugas']     
		);
	}

	$datas = table_rows_excel($row); 
	return table_builder_excel($header , $datas , 8 ,false ); 
	
}